//
//  MailCompose.m
//  Speedater
//
//  Created by NgoThang on 1/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MailCompose.h"
#import "Start.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface MailCompose (Private)

- (void)cleanup;

@end

@implementation MailCompose (Private)

- (void)cleanup
{
    self.myScrollView = nil;
    self.myTabBar = nil;
    self.nameTextField = nil;
    self.subjectTextField = nil;
    self.bodyTextView = nil;
    self.submitButton = nil;
    self.username = nil;
    self.subject = nil;
    self.pastUsernames = nil;
    self.autocompleteUsernames = nil;
    self.autocompleteTableView = nil;
}

@end


@implementation MailCompose

@synthesize myScrollView;
@synthesize myTabBar;
@synthesize nameTextField, subjectTextField;
@synthesize bodyTextView;
@synthesize submitButton;
@synthesize username, subject;
@synthesize pastUsernames, autocompleteUsernames;
@synthesize autocompleteTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"MAILCOMPOSE -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (void)hideKeyboard
{
    [nameTextField resignFirstResponder];
    [subjectTextField resignFirstResponder];
    [bodyTextView resignFirstResponder];
}

- (BOOL)validateForm
{
    if([nameTextField.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Bitte geben Sie Empfanger", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    if([subjectTextField.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil
                              message:NSLocalizedString(@"Bitte geben Sie Betreff", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    if([bodyTextView.text isEqualToString:@""] || [bodyTextView.text isEqualToString:@"Nachricht verfassen"]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil
                              message:NSLocalizedString(@"Bitte geben Sie Inhalt", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    return YES;
}

- (IBAction)submitButtonClick:(id)sender
{
    // hide keyboard
    [self hideKeyboard];
    
    // check valid form
    if (![self validateForm]) return;
    
    requestMode = 0;
    
    NSString *postString = [NSString stringWithFormat:@"op=sendMails&receiver=%@&sub=%@&content=%@&sender=%@",
                            nameTextField.text,
                            [AppDelegate encodeText:subjectTextField.text],
                            [AppDelegate encodeText:bodyTextView.text],
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];        
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)loadContacts 
{
    requestMode = 1;
    
    NSString *postString = [NSString stringWithFormat:@"op=loadMerkListe&username=%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
    
}

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring 
{
    [autocompleteUsernames removeAllObjects];
    for(NSString *curString in pastUsernames) {
        NSRange substringRange = [curString rangeOfString:substring options:NSCaseInsensitiveSearch];
        if (substringRange.location == 0) {
            [autocompleteUsernames addObject:curString];  
        }
    }
    [autocompleteTableView reloadData];
    
    if (![autocompleteUsernames count]) {
        [autocompleteTableView setHidden:TRUE];
    }
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"RADAR -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Custom notifications

- (void)keyboardWillHide:(NSNotification *)noti
{    
    NSDictionary *userInfo = [noti userInfo];
    
    // restore size of scrollview
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:self.view.bounds];
    [UIView commitAnimations];
    
    autocompleteTableView.hidden = YES;
    
    keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)noti
{
    // keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    
    // get the size of the keyboard
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // keyboard animation duration value
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // resize the scrollview
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:newTextViewFrame];
    [UIView commitAnimations];
    
    keyboardIsShown = YES;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"MAILCOMPOSE -> viewDidLoad");
    [super viewDidLoad];
    
    // scroll view
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.myScrollView setContentSize:CGSizeMake(320, 385)];
    
    // navigation title
    self.title = @"Mail schreiben";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:2]];
    
    // default values
    [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"mail_username"];
    [[NSUserDefaults standardUserDefaults] setObject:subject forKey:@"mail_subject"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [nameTextField setText:username];
    [subjectTextField setText:subject];
    
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];
    keyboardIsShown = NO;
    
    // autocomplete
    pastUsernames = [[NSMutableArray alloc] initWithObjects:nil];
    autocompleteUsernames = [[NSMutableArray alloc] init];

    autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, 320, 165) style:UITableViewStylePlain];
    autocompleteTableView.delegate = self;
    autocompleteTableView.dataSource = self;
    autocompleteTableView.scrollEnabled = YES;
    autocompleteTableView.hidden = YES;  
    autocompleteTableView.rowHeight = 40;
    [autocompleteTableView setBackgroundColor:[UIColor colorWithRed:0.341 green:0.345 blue:0.471 alpha:1]];
    autocompleteTableView.separatorColor = [UIColor grayColor];
    [self.view addSubview:autocompleteTableView];
    
    [self loadContacts];
}

- (void)viewDidUnload
{
    //NSLog(@"MAILCOMPOSE -> viewDidUnload");
    [self cleanup];
    
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil];
    
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"MAILCOMPOSE -> viewWillAppear");
    //NSLog(@"MAILCOMPOSE -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:3 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    
    
    if (textField == nameTextField) {
        [self.myScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    else {
        [self.myScrollView setContentOffset:CGPointMake(0, textField.frame.origin.y - (self.myScrollView.frame.size.height/2) + (isHideNav ? 0 : 44)) animated:YES];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    if (textField == nameTextField){
        autocompleteTableView.hidden = NO;
        
        NSString *substring = [NSString stringWithString:textField.text];
        substring = [substring stringByReplacingCharactersInRange:range withString:string];
        [self searchAutocompleteEntriesWithSubstring:substring];
    }
    
    return YES;
}

#pragma mark -
#pragma mark UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{ 
    if([textView.text isEqualToString:@"Nachricht verfassen"]) {
        textView.text = @"";
    }
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    [self.myScrollView setContentOffset:CGPointMake(0, textView.frame.origin.y - (self.myScrollView.frame.size.height/2) + (isHideNav ? 0 : 44)) animated:YES];
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{ 
    // keyboard will hide
    if([textView.text isEqualToString:@""]) {
        textView.text = @"Nachricht verfassen";
    }
} 

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:2]];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 2;
            break;
        case 2: 
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	
    
    if (requestMode == 1) 
    {
        [pastUsernames removeAllObjects];
        for (NSDictionary *dict in [responseString JSONValue]) {
            [pastUsernames addObject:[dict objectForKey:@"myUsername"]];
        }
        [responseString release];
    }
    else
    {
        NSMutableDictionary *results = [responseString JSONValue];
        [responseString release];
        
        if ([[results objectForKey:@"status"] isEqualToString:@"1"]) 
        {
            [self goBack];
            
            UIAlertView *alert = [[UIAlertView alloc] 
                                  initWithTitle:nil 
                                  message:NSLocalizedString(@"Sent mail successfully!", nil) 
                                  delegate:nil 
                                  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                  otherButtonTitles:nil];
            [alert show];	
            [alert release];
        }
        else 
        {
            UIAlertView *alert = [[UIAlertView alloc] 
                                  initWithTitle:nil 
                                  message:NSLocalizedString(@"Incidents occur, please check again!", nil) 
                                  delegate:nil 
                                  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                  otherButtonTitles:nil];
            [alert show];	
            [alert release];
        }
    }
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section 
{
    return autocompleteUsernames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];        
    }
    
    cell.textLabel.text = [autocompleteUsernames objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    
    return cell;
}

#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    nameTextField.text = selectedCell.textLabel.text;
    [autocompleteTableView setHidden:TRUE];
}

#pragma mark UIScrollViewDelegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 
{
    if (scrollView == myScrollView) {
        autocompleteTableView.hidden = YES;
    }
}


#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
